package org.aaron.wbclient.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

public class ApacheUtils {
	public static List<NameValuePair> convertMapToNameValuePairs(Map<String, String> oauthMap) {
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		Iterator<Entry<String, String>> it = oauthMap.entrySet().iterator();
		while (it.hasNext()) {
			Entry<String, String> entry = it.next();
			NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue());
			pairs.add(pair);
		}
		return pairs;
	}

	public static String getResponseText(HttpResponse response) {
		HttpEntity responseEntity = response.getEntity();
		InputStream input = null;
		String result = null;
		try {
			input = responseEntity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(input));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	public static String parseStringFromEntity(HttpEntity entity) {
		String result = null;
		try {
			InputStream input = entity.getContent();
			BufferedReader reader = new BufferedReader(new InputStreamReader(input));
			String line = null;
			StringBuffer sb = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
			result = sb.toString();
		} catch (Exception e) {
			System.out.println(e);
		}
		return result;
	}
}
